import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { ConfigService } from 'app/config/config.service';

// declare const Paho: any;
declare const Stomp: any;

@Injectable({
    providedIn: 'root'
})
export class StompClientService {
    // private url = 'ws://192.168.0.56:61614/stomp';
    private url = `${this.config.apiUrl.activeMq}/stomp`;
    login = this.config.apiUrl.activeMq_user;
    passcode = this.config.apiUrl.activeMq_Pwd;
    client: any;
    constructor(private config: ConfigService) {}

    /**
     * 根据传入的topic来订阅client消息
     */
    createClient(topic: string): Observable<any> {
        // 创建websocket服务
        /* this.client = new Paho.MQTT.Client(
			this.host, // host
			61614, // port
			'', // path
			`web${this.tools.isGuid(12)}` // client id
		); */

        this.client = Stomp.client(this.url);
        const _cs = new Subject<any>();

        this.client.connect(
            this.login,
            this.passcode,
            _frame => {
                this.client.subscribe('/topic/' + topic, msg => {
                    _cs.next(msg.body);
                });
            },
            err => {
                _cs.error(err);
            }
        );

        return _cs.asObservable();

        // this.ws.onopen = event => {};
        /* return new Observable(observer => {
			// 返回成功时执行的方法
			this.client.onMessageArrived = event => observer.next(event.data);
			// 返回错误时执行的方法
			this.client.onerror = event => observer.error(event);
			// 关闭websocket流时执行的方法
			this.client.close = event => observer.complete();
			const _this = this;
			return {
				unsubscribe: () => {
					this.closeSocket();
				}
			};
		}); */
    }

    /**关闭 */
    closeSocket() {
        this.client.disconnect(() => {});
    }

    /**发送消息 */
    sendMessage(msg: string) {}
}
